import Router from 'koa-router';
import axios from './utils/axios'
import Cart from '../dbs/models/cart'
import Order from '../dbs/models/order'
import md5 from 'crypto-js/md5'

let router = new Router({prefix: '/order'})

router.post("/createOrder", async ctx => {
    console.log(ctx.request.body)
    let {id, price, count} = ctx.request.body,
        time = Date(),
        orderId = md5(Math.random()+time)
    if(!ctx.isAuthenticated()){
        ctx.body = {
            code:-1,
            msg:"please Login"
        }
    } else {
        let findCart = await Cart.find({CartNo:id})
        if(findCart){
            order = await new Order({
                id:orderId,
                count,
                total:price*count,
                time,
                user:ctx.session.passport.user,
                name:findCart.detail[0].name,
                imgs:findCart.detail[0].imgs,
                status:0
            })
        } else {
            ctx.body = {
                code:-1,
                msg:"购物车数据获取失败"
            }
        }
        try {
            let result = await order.save()
            if(result){
                await findCart.remove();
                ctx.body = {
                    code:0,
                    id:orderId
                }
            } else {
                ctx.body = {
                    code:-1,
                    msg:"订单创建失败"
                }
            }
        } catch (error) {
            ctx.body = {
                code:-1,
                msg:"服务器存储异常"
            }
        }
    }

})

router.post("/getOrders", async ctx => {
    if(!ctx.isAuthenticated()){
        ctx.body = {
            code:-1,
            msg:"please Login"
        }
    } else {
        try {
            let result = await Order.find()
            if(result){
                ctx.body = {
                    code:0,
                    list:result
                }
            } else {
                ctx.body = {
                    code:0,
                    list:[]
                }
            }
        } catch (error) {
            ctx.body = {
                code:0,
                list:[]
            }
        }
    }
})

export default router
